import { Module } from 'vuex'
import router from '@/router'

import { IRootState } from '../types'
import { ILoginState, IAccount } from './types'

import localCache from '@/utils/cache'

import { accountLoginRequest } from '@/api/login/login'

import { ElMessage } from 'element-plus'

const loginModule: Module<ILoginState, IRootState> = {
  namespaced: true,
  state() {
    return {
      token: '',
    }
  },
  getters: {},
  mutations: {
    changeToken(state, token: string) {
      localCache.setCache('token', token)
      state.token = token
    },
  },
  actions: {
    async accountLoginAction({ commit }, payload: IAccount) {
      // 1.发送登陆请求
      const loginResult = await accountLoginRequest(payload)
      // 2.获取用户token
      const { token } = loginResult.data
      if (loginResult.success) {
        ElMessage({
          type: 'success',
          message: 'login success',
          showClose: true,
        })
      } else {
        ElMessage({
          type: 'error',
          message: loginResult.message,
          showClose: true,
        })
      }
      // 3.保存token
      commit('changeToken', token)

      // 4.路由跳转
      router.push('/home')
    },
  },
}

export default loginModule
